﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SnippetBox.Core.Common.Extensions;
using SnippetBox.Core.Common.Paging;
using SnippetBox.Core.Common.Security;
using SnippetBox.Core.Data.Models;
using SnippetBox.Core.Data.Service;
using SnippetBox.Web.Areas.Manage.Models;
using SnippetBox.Web.Models;

namespace SnippetBox.Web.Areas.Manage.Controllers {
    [Authorize(Roles = Roles.SUPER_ADMIN )]
    public class UsersController : Controller {
        readonly UserService _userService = new UserService();

        public ActionResult Index(int? page, string query) {
            if (query.IsNullOrEmpty())
                ViewData.Model = _userService.GetAllPaged(page);
            else
                ViewData.Model = _userService.SearchByUsername(query, page);

            return View();
        }
        
        public ActionResult Create() {
            return View(new UserModel());
        }

        [HttpPost]
        public ActionResult Create(UserModel userModel) {
            if (userModel.Password.IsNullOrEmpty())
                ModelState.AddModelError("Password", "Please fill in a password.");

            if (!ModelState.IsValid)
                return View(userModel);

            var user = new User();

            user.Username = userModel.User.Username;

            if (!userModel.Password.IsNullOrEmpty())
                user.PasswordHashed = Hash.Make(userModel.Password);

            user.DateCreated = DateTime.Now;
            user.Role = userModel.User.Role;
            user.Email = userModel.User.Email;
            user.Website = FixWebsiteUrl(userModel.User.Website);
            user.TwitterUsername = FixTwitterUsername(userModel.User.TwitterUsername);
            _userService.Create(user);
            _userService.Save();

            return RedirectToAction("Index");
        }
        
        public ActionResult Edit(int id) {
            var user = _userService.GetById(id);

            if (user == null)
                return View("NotFound", new NotFoundModel());

            var model = new UserModel(user);
            
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(int id, UserModel userModel) {
            if (!ModelState.IsValid)
                return View(userModel);

            var user = _userService.GetById(id);

            user.Username = userModel.User.Username;

            if (!userModel.Password.IsNullOrEmpty())
                user.PasswordHashed = Hash.Make(userModel.Password);

            user.Role = userModel.User.Role;
            user.Email = userModel.User.Email;
            user.Website = FixWebsiteUrl(userModel.User.Website);
            user.TwitterUsername = FixTwitterUsername(userModel.User.TwitterUsername);
                
            _userService.Save();

            return RedirectToAction("Index");
        }

        public ActionResult Delete(int id) {
            var user = _userService.GetById(id);

            if (user == null)
                return View("NotFound", new NotFoundModel());

            return View(user);
        }
        
        [HttpPost, ActionName("Delete")]
        public ActionResult DeletePost(int id) {
            var user = _userService.GetById(id);

            if (user == null)
                return View("NotFound", new NotFoundModel());

            user.IsDeleted = !user.IsDeleted;
            _userService.Save();

            if (Request.IsAjaxRequest())
                return Json(new { subject = "The user " + user.Username, predicate = "was deleted" });

            return RedirectToAction("Index");
        }

        public ActionResult UsernameFree(User user) {
            return Json(!_userService.UsernameExists(user.Username, user != null ? (int?)user.UserId : null), JsonRequestBehavior.AllowGet);
        }

        private string FixWebsiteUrl(string url) {
            if (url.IsNullOrEmpty())
                return null;

            if (!url.StartsWith("http"))
                url = "http://" + url;

            return url;
        }

        private string FixTwitterUsername(string username) {
            return !username.IsNullOrEmpty() ? username.Replace("@", "") : username;
        }
    }
}
